{
 "cells": [
  {
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-09-10T11:29:47.392185Z",
     "start_time": "2025-09-10T11:29:47.388893Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import re\n",
    "\n",
    "# 你不用太关心这个函数\n",
    "def parse(text):\n",
    "    # 使用正则表达式去除标点符号和换行符\n",
    "    text = re.sub(r'[^\\w ]', ' ', text)\n",
    "\n",
    "    # 转为小写\n",
    "    text = text.lower()\n",
    "\n",
    "    # 生成所有单词的列表\n",
    "    word_list = text.split(' ')\n",
    "\n",
    "    # 去除空白单词\n",
    "    word_list = filter(None, word_list)\n",
    "\n",
    "    # 生成单词和词频的字典\n",
    "    word_cnt = {}\n",
    "    for word in word_list:\n",
    "        if word not in word_cnt:\n",
    "            word_cnt[word] = 0\n",
    "        word_cnt[word] += 1\n",
    "\n",
    "    # 按照词频排序\n",
    "    sorted_word_cnt = sorted(word_cnt.items(), key=lambda kv: kv[1], reverse=True)\n",
    "\n",
    "    return sorted_word_cnt\n",
    "\n",
    "with open('in.txt', 'r') as fin:\n",
    "    text = fin.read()\n",
    "\n",
    "word_and_freq = parse(text)\n",
    "\n",
    "with open('out.txt', 'w') as fout:\n",
    "    for word, freq in word_and_freq:\n",
    "        fout.write('{} {}\\n'.format(word, freq))"
   ],
   "id": "initial_id",
   "outputs": [],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-10T11:27:57.915890Z",
     "start_time": "2025-09-10T11:27:57.914591Z"
    }
   },
   "cell_type": "code",
   "source": "",
   "id": "bc5c4361b273e8ec",
   "outputs": [],
   "execution_count": null
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
